package rs.mbs2.epics.server.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import rs.mbs2.epics.server.entity.Photo;
import rs.mbs2.epics.server.entity.Tag;
import rs.mbs2.epics.server.session.dao.localinterface.PhotoDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.TagDaoLocal;

@SuppressWarnings("serial")
public class TagPhotoController extends HttpServlet {
	
	private static Logger log = Logger.getLogger(TagPhotoController.class);
	
	@EJB
	PhotoDaoLocal photoDao;
	
	@EJB
	TagDaoLocal tagDao;
	
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		// dodavanje tag-a : provera da li postoji vec sa takvim tekstom; true-koristi,false-pravi novi

		
		String tagText = request.getParameter("tagtext");
		int photoId = Integer.parseInt(request.getParameter("photoId"));
		Photo photo = photoDao.findById(photoId);
		
		List<Tag> tagovi = tagDao.findTagByText(tagText);
		
		if(!tagovi.isEmpty()) {			
			Tag postojeciTag = tagovi.get(0);
			postojeciTag.getTaggedPhotos().add(photo);
			tagDao.merge(postojeciTag);
			
		} else {
			Tag noviTag = new Tag(tagText);
			noviTag.getTaggedPhotos().add(photo);
			tagDao.persist(noviTag);			
		}
		
		log.info(new Date() + " dodat tag: " + tagText + " na sliku[id]:" + photoId);
		response.sendRedirect("./ViewPhotoController?id=" + photoId);
		
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
